package main

import (
	"fmt"
	"github.com/gorilla/mux"
	"go-kit/demo7/utils"
	"log"
	netHttp "net/http"
	"os"
	"os/signal"
	"syscall"
)

//挂起一个HTTP 服务 并把请求 传递给service 层
func main() {

	//user := Services.UserService{}
	//	endp := Endpoint2.GetUserEndPoint(user)

	//serverHandler := http.NewServer(endp, Transport2.DecodeUserTransport, Transport2.EncodeUserTransport)

	r := mux.NewRouter()

	//所有方式都能访问
	//r.Handle(`/user`, serverHandler)

	//GET 方式访问
	r.Methods("GET").Path(`/user/{uid:\d+}`).HandlerFunc(func(writer netHttp.ResponseWriter, request *netHttp.Request) {

		writer.Header().Set("Content-type", "application/json")
		writer.Write([]byte(`{"status":"OK"}`))

	})
	r.Methods("GET").Path(`/health`).HandlerFunc(func(writer netHttp.ResponseWriter, request *netHttp.Request) {

		writer.Header().Set("Content-type", "application/json")
		writer.Write([]byte(`{"status":"OK"}`))

	})

	errChan := make(chan error)

	go func() {
		//调用注册服务
		utils.RegService()

		err := netHttp.ListenAndServe(":8080", r)

		if err != nil {
			log.Println(err)
			errChan <- err
		}
	}()

	go func() {
		sigChan := make(chan os.Signal)

		signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

		errChan <- fmt.Errorf("%s", <-sigChan)

	}()

	getErr := <-errChan

	utils.UnRegService()

	log.Println(getErr)
}
